// 定时任务 每10分钟爬取网页的股票价格
import schedule from 'node-schedule';
import gupiaoListDao from "../Dao/gupiaoList.js";
import gupiaoDao from "../Dao/gupiao.js";
import {sendEmail_post} from "../utils/utils.js";
// import {getPriceAndName} from "../utils/gupiaoUtils.js";
import {config} from "../config/index.js";
import userDao from "../Dao/user.js";
import {useGetEmail} from "../api/api_user/useUser.js";
import {getPriceGuPiao} from "../api/api_gupiao/useGuPiao.js";

export const timer_getPrice = async () => {
  // 启动一个定时任务 5分钟执行一次 立即执行
  const job = schedule.scheduleJob(`*/${config.TIMER_GAP} * * * *`, async function () {
    // console.log('定时任务执行了');
    // 获取股票列表
    let guPiaoList = await getGuPiaoList();
    // console.log(guPiaoList, "timer_getPrice");
    for (let i = 0; i < guPiaoList.length; i++) {
      let gupiao_id = guPiaoList[i].gupiao_id;
      // console.log('股票ID:' + gupiao_id);
      // let {price, name, result} = await getPriceAndName(gupiao_id);
      let {price, name, result} = await getPriceGuPiao(gupiao_id);
      if(result === false) {
        console.log('获取股票价格失败');
        continue;
      }
      console.log(`定时任务执行，股票ID:${gupiao_id},股票名称：${name},股票价格：${price}`);
      // 更新股票的价格和名称
      await gupiaoListDao.update(gupiao_id, name, price);
      // todo 获取所有用户的数据然后分别进行判定，然后发送邮件
      // 获取所有买入了并且当前价格在卖出价格上下限之外的用户id
      let sellUserList = await getSellUser(gupiao_id, price);
      // 获取所有未买入并且当前价格在买入价格之下的用户id
      let buyUserList = await getBuyUser(gupiao_id, price);

      // 发送卖出邮件
      sendSellEmails(sellUserList, price, name, gupiao_id);
      // 发送买入邮件
      sendBuyEmails(buyUserList, price, name, gupiao_id);
    }
  });
};

// 获取所有的股票
const getGuPiaoList = () => {
  return gupiaoListDao.get();
};

const getSellUser = async (gupiao_id, price) => {
  let list = await gupiaoDao.getSellUser(gupiao_id, price);
  // console.log(list, 'getSellUser');
  return list.rows.map(item => item.user_id);
};

const getBuyUser = async (gupiao_id, price) => {
  let list = await gupiaoDao.getBuyUser(gupiao_id, price);
  // console.log(list, 'getBuyUser');
  return list.rows.map(item => item.user_id);
};

const sendSellEmails = async (idList, price, name, gupiao_id) => {
  for(let i = 0; i < idList.length; i++) {
    let id = idList[i];
    let email = await getEmailByID(id, gupiao_id);
    // console.log(email, 'sendSellEmails');
    if(!email) continue;
    await userDao.updateUserNexttime(id, Date.now() + config.EMAIL_GAP_TIME, gupiao_id);
    sendEmailSell(email, price, id, gupiao_id, name);
  }
};

const sendBuyEmails = async (idList, price, name, gupiao_id) => {
  for(let i = 0; i < idList.length; i++) {
    let id = idList[i];
    let email = await getEmailByID(id, gupiao_id);
    // console.log(email, 'sendBuyEmails');
    if(!email) continue;
    // console.log(id, name, email, Date.now() + config.EMAIL_GAP_TIME);
    await userDao.updateUserNexttime(id, Date.now() + config.EMAIL_GAP_TIME, gupiao_id);
    sendEmailBuy(email, price, id, gupiao_id, name);
  }
};

// 获取id对应的邮箱
const getEmailByID = async (id, gupiao_id) => {
  let result = await userDao.getUserEmailWithGuPiaoId(id, gupiao_id);
  if(result) {
    if(result.nexttime && result.nexttime > Date.now() ) {
      return "";
    }
    return result.email;
  }
  let email = await useGetEmail(id);
  if(email) {
    // console.log(id, email, gupiao_id);
    await userDao.addUser(id, email, gupiao_id);
  }
  return email;
};

const sendEmailBuy = (email, price, id, gupiao_id, gupiao_name) => {
  sendEmail_post(email, `
  用户 ${id} 你好：
    欢迎使用无风股票监控软件。
    您的股票 ${gupiao_id} ${gupiao_name} 已经到达了买点，请及时处理，当前价格：${price}.
    祝好！
  `);
};

const sendEmailSell = (email, price, id, gupiao_id, gupiao_name) => {
  sendEmail_post(email, `
  用户 ${id} 你好：
    欢迎使用无风股票监控软件。
    您的股票 ${gupiao_id} ${gupiao_name} 已经到达了卖点，请及时处理，当前价格：${price}.
    祝好！
  `);
};

timer_getPrice();


